package com.example.demo.controller;
import java.io.IOException;

import javax.servlet.ServletContext;

import com.example.demo.dao.ProductDao;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.example.demo.Product;
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductDao productDao;

    @GetMapping("/add")
    public String showAddProductForm(Model model) {
        model.addAttribute("product", new Product());
        return "addProduct";
    }

    @PostMapping("/add")
    public String addProduct(@ModelAttribute("product") Product product, BindingResult result) {
        if (result.hasErrors()) {
            return "addProduct";
        }
        productDao.addProduct(product);
        return "redirect:/product/list";
    }

    @GetMapping("/list")
    public String productList(Model model) {
        List<Product> productList = productDao.getAllProducts();
        model.addAttribute("productList", productList);
        return "productList";
    }

}